import zipfile
import sqlite3
from reedsolo import RSCodec ,ReedSolomonError
from tqdm import tqdm #tqdm
import base64
import logging
import pprint
import wx
from hashlib import blake2b as hash_
from inc import *

logging.basicConfig(level=logging.INFO)
db = sqlite3.connect("blake2.log.db", check_same_thread=False)
cur = db.cursor()
# ecc=RSCodec(32)#纠错码字长度，可纠正len/2个误读
info={'root':"D:/git/python/hash/"}


# def creatZip():
#     with zipfile.ZipFile('spam.7z', 'w',compression=zipfile.ZIP_LZMA,allowZip64=True) as myzip:
#         myzip.writestr('eggs.txt',"asdfsasdf")

def OutPutDatabase(db,root):
    cur=db.cursor()
    result = cur.execute("select count(*) from hash ")
    row = result.fetchone()
    total = row[0]
    lens=int(total/BackupFileSize)+1
    dlg = wx.ProgressDialog("导出校验记录", " ", maximum = total,parent=None,style = 0| wx.PD_APP_MODAL | wx.PD_ESTIMATED_TIME| wx.PD_REMAINING_TIME )
    dlgn=0
    with tqdm(total=total) as bar:
        with zipfile.ZipFile(f"{root}\\{logfilename[:-4]}bak.zip", 'w',allowZip64=True) as myzip:  #compression=zipfile.ZIP_LZMA,
            myzip.writestr(f"config.txt",f"{row[0]}")
            for i in range(lens):
                sql_str=""
                result = cur.execute(f"select * from hash LIMIT {BackupFileSize*i}, {BackupFileSize}") 
                row=result.fetchall()
                for n in row:
                    bar.update(1)
                    dlgn=dlgn+1
                    dlg.Update(dlgn,f"{dlgn}/{total}")
                    try:
                        text1=eccBase64En(n)
                        sql_str=sql_str+f"{n[0]}\t{text1}\n"
                    except:
                        logging.error(n[0])
                myzip.writestr(f"{i}.log",sql_str)
                
            
def InPutDatabase(db,root):
    with zipfile.ZipFile(f"{root}\\blake2bak.zip", 'r') as myzip:
        info=myzip.namelist()
        info.remove('config.txt')
        trySql(db,"DROP TABLE IF EXISTS \"temp_input\";")
        trySql(db,"create table temp_input (path varchar(256) primary key, hash varchar(128))")
        # with myzip.open('config.txt') as path:
            # pbar = tqdm(total=int(path.readline())) 
        pbar = tqdm(total=int(len(info))) 
        for file in info:
            dataary=[]
            sql="INSERT INTO temp_input (path,hash) VALUES (?, ? )"

            with myzip.open(file) as filecontent:
                filecontent=filecontent.readlines()
                for rows in filecontent:
                    part_=rows.decode().split("\t")
                    ins=eccBase64De(part_[1])
                    # logging.info(ins)
                    if(ins == False):
                        logging.error(f"{rows.decode()}")
                    else:
                        dataary.append((part_[0],ins[0]))
            try:
                db.executemany(sql,dataary)
            except sqlite3.Error as er:
                logging.error(er)
                db.rollback()
            else:
                db.commit()
            pbar.update(1)
        pbar.close()


def eccBase64En(row):
    try:
        en=f"{base64.b64encode(ecc.encode(bytes.fromhex(row[1]))).decode()}"
    except :
        logging.error(f"RScode编码错误！")
    else:
        return en
def eccBase64De(str):
    try:
        rsdecode=ecc.decode(base64.b64decode(str))
        if(rsdecode[2] != b''):
            logging.error(f"ECC 发现错误! :\n{str}\n{base64.b64encode(rsdecode[1]).decode()}")
            d3=False
        else:
            d3=True
    except ReedSolomonError :
        logging.error("ECC 纠错失败")
        return False
    except Exception as e:
        logging.error(f"RScode解码错误:{e}")
    else:
        d1=rsdecode[0].hex().upper()
        d2=base64.b64encode(rsdecode[1]).decode()
        return (d1,d2,d3)
    

if __name__ == "__main__":
    ecc=RSCodec(8)
    app=wx.PySimpleApp()
    root=r"D:\hubo"
    db = sqlite3.connect(f"{root}\\blake2.log.db", check_same_thread=False)
    OutPutDatabase(db,root)
    InPutDatabase(db,root)
    #en=eccBase64En((r'\HUAWEI_nova_2_Plus\Pictures\.Gallery2\recycle\GF6DA7BRG44DEMJQPQYTKMZUG42TSOBTHA3DAN34KNRXEZLFNZZWQ33UL4ZDAMJYGA3DEMBNGE3DANRQGIXHA3THPQXHA3THPRUW2YLHMUXXA3THPRXHK3DM',"3B1E0414E8A90C51F350AE214C123CEBB868C9441F4D3820D64CC4185E4DF44DCC26F447E3686CC1391806002BF84A521966FDFBE7E659FEDF5EAC6DBFB553F3"))
    # en=eccBase64En((r'\HUAWEI_nova_2_Plus\Pictures\.Gallery2\recycle\GF6DA7BRG44DEMJQPQYTKMZUG42TSOBTHA3DAN34KNRXEZLFNZZWQ33UL4ZDAMJYGA3DEMBNGE3DANRQGIXHA3THPQXHA3THPRUW2Y000000011111111',"3B1E0414E8A90C51F350AE214C123CEBB868C9441F4D3820D64CC4185E4DF44DCC26F447E3686CC1391806002BF84A521966FDFBE7E659FEDF5EAC6DBFB553F3"))
    # en=eccBase64En((r"\WPS_BAK\.587276\cachebackup\漫游文档.20190301023725632.bak\模板.docx","5C9B8804480A61E62F444435B6FFF0E28D15D89DE1E4FB439BF80D74FF36E726FA21AAE0FD7ECA7164E0119CBDAC50EC8AAAAC01E155EBB8D808F5D8420A6E9D"))
    # en=eccBase64En((r"\document\文档\2018年职称下发资料\bak\职称相关文件\9.8云南省教育厅++云南省人力资源和社会保障厅关于云南省中小学幼儿园岗位设置结构比例指导标准的补充意见（云教人〔2017〕29号）.PDF","B658BA7449E463D677E274EEB96CF429997A5A040C0D34AD44F2324EAD710ECBC296374EAE9F503CB8710DB2CAD913F01986101CC059B2D424B5BC1FCC8D1068"))
    # logging.info(en)
    # de=eccBase64De(en)
    # logging.info(de)